<template>
    <div>
        <div class="search">
            <input
                v-model="keyword"
                type="text"
                placeholder="输入城市名或者拼音"
                class="search-input"
            />
        </div>
        <div class="search-content" ref="search">
            <ul>
                <li class="search-item" v-for="item of list" :key="item.id">
                    {{ item.name }}
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import BScroll from "better-scroll";
import { isEmptyObject } from "@/utils";
export default {
    name: "search",
    props: {
        cities: Object,
    },
    data() {
        return {
            keyword: "",
            list: [],
            timer: null,
        };
    },
    mounted() {
         this.scroll = new BScroll(this.$refs.search, {});
    },
    watch: {
        keyword() {
            if (this.timer) {
                clearTimeout(this.timer);
            }
            this.timer = setTimeout(() => {
                const result = [];
                for (let i in this.cities) {
                    this.cities[i].forEach((value) => {
                        if (
                            value.spell.indexOf(this.keyword) > -1 ||
                            value.name.indexOf(this.keyword) > -1
                        ) {
                            result.push(value);
                        }
                    });
                }
                this.list = result;
            }, 100);
        },
        cities: {
            handler(val) {
                if (!isEmptyObject(val)) {
                    console.log(val, "valvalval2");
                    this.$nextTick(() => {
                        this.scroll = new BScroll(this.$refs.search, {});
                    });
                }
            },
            deep: true,
            immediate: true,
        },
    },
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/main.scss";
.search {
    padding: 5px;
    background-color: $background;
    .search-input {
        width: 100%;
        height: 31px;
        line-height: 31px;
        border-radius: 3px;
        color: #666;
        text-align: center;
        border: 0;
        padding: 0 5px;
    }
}
.search-content {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    top: 86px;
    height: 100%;
    overflow: hidden;
    background: #eee;
    z-index: 1;
    .search-item {
        line-height: 31px;
        padding-left: 10px;
        color: #666;
        background: #fff;
        border-bottom: 1px solid rgb(158, 158, 158);
        font-size: 14px;
    }
}
</style>